package com.starwish.starwishblog.web.front;

import com.starwish.starwishblog.result.ResultResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {

    @Value("${starwish.user}")
    String path;

    @PostMapping("/article")
    public ResultResponse<String> upload(@RequestParam(value = "userImg") MultipartFile multipartFile){
        ResultResponse<String> result = null;
        try {
            String filename = multipartFile.getOriginalFilename();
            filename = UUID.randomUUID().toString().replace("-", "")+filename.substring(filename.lastIndexOf("."));
            File file = new File(path);
            if(!file.exists()){
                file.mkdir();
            }
            File f = new File(file,filename);
            multipartFile.transferTo(f);
            String url = "http://localhost:8888/img/star_wish/user/"+filename;
            result = new ResultResponse<>(200,"上传成功!",url);
        }catch (IOException e){
            e.printStackTrace();
            result = new ResultResponse<>(202,"上传异常!");
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(202,"上传异常!");
        }
        return result;
    }
}
